/**
 * 删除字符串中头尾的的 空格 或 指定的字符
 * 
 * @param {string} string 要处理的字符串
 * @param {string} [chars=whitespace] 要移除的字符
 * @returns {string} 移除头尾指定字符后的字符串
 * @example
 *   trim("  a    ") => "a"
 *   trim("11111122222abc22221212", "12") => "abc"
 */
export function trim(string: string, chars?: string) {
  if (string && chars === undefined) return string.trim();
  const strSymbols = string.split("");
  const chrSymbols = chars?.split("") || [];
  const start = charsStartIndex(strSymbols, chrSymbols);
  const end = charsEndIndex(strSymbols, chrSymbols) + 1;
  return string.slice(start, end);
}

function charsStartIndex(strSymbols: string[], chrSymbols: string[]) {
  let index = -1;
  const length = strSymbols.length;
  while (++index < length && chrSymbols.indexOf(strSymbols[index]) > -1) {}
  return index;
}

function charsEndIndex(strSymbols: string[], chrSymbols: string[]) {
  let index = strSymbols.length;
  while (index-- && chrSymbols.indexOf(strSymbols[index]) > -1) {}
  return index;
}
